<?php
/*
 * ---------------------------------------------------------------
 * Author  : Anthony Tran
 * Email   : Incredibletran@gmail.com - Incredibletran@hotmail.com
 * Version : 1.2
 * ---------------------------------------------------------------
*/
require_once(APPPATH.'controllers/admin_controller'.EXT);
class	Video extends Admin_controller{
	public function __construct(){
		parent::__construct();
		$this->load->model(array('video_model'));
		$this->load->library(array('session','upload', 'message'));
		$this->load->helper(array('link','upload','text','im'));
		ini_set("memory_limit","256M");
		ini_set("time_execution", 3600);
		session_start();
		if($this->session->userdata('language')){
			$language   =   $this->session->userdata('language');
		}else{
			$language  =   '';
		}
		
		if ($language == LANG) {
			$this->lang->load(LANG, LANG_FOLDER);
		}else{
			$this->lang->load(LANG_DEFAULT, LANG_FOLDER_DEFAULT);
		}
	}
	
	function index(){
		#get status filter
		if(isset($_REQUEST['status'])){
			$status = $_REQUEST['status'];
			if($status == 'active'){$status = 'yes';}elseif ($status == 'pending'){$status = 'no';}
			$this->session->set_userdata('status', $status);
		}else{
			if($this->session->userdata('status')){
				$status = $this->session->userdata('status');
			}else {
				$status = 'all';
				$this->session->set_userdata('status', $status);
			}
		}
		
		#get keyword filter
		if(isset($_REQUEST['search'])){
			$keyword	=	$_REQUEST["search"];
			$keyword	=	str_replace("Keyword", "", $keyword);
			$this->session->set_userdata('keyword_video', $keyword);
		}else {
			if($this->session->userdata('keyword_video')){
				$keyword	=	$this->session->userdata('keyword_video');
			}else{
				$keyword	=	"";
				$this->session->set_userdata('keyword_video', $keyword);
			}
		}
		
		#get date filter
    	if(isset($_REQUEST['date'])){
    		$date	=	$_REQUEST['date'];
    		$date	=	str_replace("Date/time", "", $date);
    		$this->session->set_userdata('date_video',$date);
    	}else {
    		if($this->session->userdata('date_video')){
    			$date	=	$this->session->userdata('date_video');
    		}else {
    			$date	=	"";
    			$this->session->set_userdata('date_video', $date);
    		}
    	}
		
		#get number item on perpage.
		if(isset($_REQUEST['perpage'])) {
			$perpage		= 	$_REQUEST['perpage'];
			$this->session->set_userdata('video_perpage',$perpage);
		} else {
			if($this->session->userdata('video_perpage')) {
				$perpage	= 	$this->session->userdata('video_perpage');
			} else {
				$perpage 	= 	'all';
				$this->session->set_userdata('video_perpage',$perpage);
			}
		}
		
		#get total item in DB.
		$total_page					= 	count($this->video_model->get_all($status, $keyword, $date));
		$this->load->library('pagination');
		$config['total_rows'] 		= 	$total_page;
		$config['per_page'] 		= 	$perpage;
		$config['first_link']		= 	$this->lang->line('first');
		$config['last_link']		= 	$this->lang->line('last');
		$config['next_link']		= 	$this->lang->line('next');
		$config['prev_link']		= 	$this->lang->line('prev');
		$config['first_tag_open']	= 	'<span>';
		$config['first_tag_close']	= 	'</span>';
		$config['last_tag_open']	= 	'<span>';
		$config['last_tag_close']	= 	'</span>';
		$config['num_tag_open']		= 	'<span style="padding:0 2px 0 2px">';
		$config['num_tag_close']	= 	'</span>';
		$config['num_links']		= 	4;
		$config['cur_tag_open']		= 	'<a class="currentpage">';
		$config['cur_tag_close']	= 	'</a>';
		$config['base_url']			= 	admin_url().'/video/';
		$config['uri_segment']		= 	3;
		$this->pagination->initialize($config);
		
		$pagination					= 	$this->pagination->create_links();
		$offset 					= 	($this->uri->segment(3)=='') ? 0 : $this->uri->segment(3);
		
		#get data.
		$video_list					=	$this->video_model->get_list($perpage, $offset, $status, $keyword, $date);
		 
		$video_url					=	$this->selfURL();
		$this->session->set_userdata('video_url', $video_url);
		$delete_video				=	$this->session->userdata('delete_video');
		$this->session->unset_userdata('delete_video');
		
		if(isset($delete_video) && $delete_video == 'delete video'){
			$inform	=	'delete video success';
		}else {
			$inform = "";
		}
		
		$data['date']				=	$date;
		$data['keyword']			=	$keyword;
		$data['current_perpage']	=	$perpage;
		$data['pagination']			=	$pagination;
		$data['current_url']		=	$video_url;
		$data['slide_list']			=	$video_list;
		$data['inform']				=	$inform;
		$data['act']				=	"video";
    	$data['tpl_file']			=	"index";
    	$this->load->view('admin/admin_layout/index', $data);
	}
	
	
	
	function add(){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			#Validate 
			$this->form_validation->set_rules('name',$this->lang->line('name'), 'required|trim|xss_clean');
			$this->form_validation->set_rules('description', $this->lang->line('description'), 'trim|xss_clean');
			$this->form_validation->set_rules('video_url', $this->lang->line('video_url'), 'trim|xss_clean');
			if($this->form_validation->run() == TRUE){
    			 $video_name  	= 	$this->input->post('name');
	             $image 		= 	$this->input->post('image');
			     $image 		= 	str_replace(base_url(),"",$image);   
			     $video_url 	= 	$this->input->post('video_url');
			     $video_url		=	str_replace("Video Url", "", $video_url);
			     
			     if($_FILES['video_file']['name'] == "" && $video_url == ""){
			     	die('Video is required.');
			     }
			     if($_FILES['video_file']['size'] >= 1024*1024*200){
			     	die("Video's size must less than 200MB.");
			     }
	             $info			= 	array(
						                    'name'          => $video_name,
						                    'image_url'     => $image,
						                    'video_url'     => $video_url,
						                    'order'         => $this->input->post('order'),
						             		'date_create'   => date('Y-m-d'),
						                    'active'        => $this->input->post('status'),
	             							'description'	=> $this->input->post('description')
	                					 );
				if($this->video_model->check_exist($this->input->post('name'))) {
    				die('This name is exist!');
    			}elseif ($this->video_model->check_order_exist($this->input->post('order'))){
    				die('This order is exist!');
    			}else{
    				if($_FILES['video_file']['name'] != ""){
    					$upload_data 	= 	$this->uploading();
    					$info['video']  = 	$upload_data['video_path'];
    				}
    				$this->video_model->add($info);
    				die('yes');
    			}
			}else {
				die(validation_errors());
			}
		}
		$data['no']	=	"";
		$this->load->view('add', $data);
	}
	
	
	function uploading(){
		# Note: Need to config file type in the configs/mimines.php
		# You need to connsider some command line on .htaccess file as well
		#->	php_value upload_max_filesize 1024M
		#->	php_value post_max_size 1024M
		#->	php_value max_execution_time 600
		#->	php_value max_input_time 600
		$upload_dir = 'uploads/videos';
		if(!is_dir($upload_dir)){
			create_dir($album_dir);
		}
		$return = array();
		
		# Upload video
		$video_config['upload_path']	= 	$upload_dir;
		$video_config['allowed_types']	= 	'flv|mp4|avi';
		$video_config['file_name']		=	ascii_link($_FILES["video_file"]["name"]);
		$video_config['max_size']		= 	'204800';
		
		$this->load->library('upload', $video_config);
		$this->upload->initialize($video_config);
		if (!$this->upload->do_upload('video_file')) {
			die($this->upload->display_errors());
		}else {
			$video_data 				= 	$this->upload->data();
			$return['video_path'] 		= 	'uploads/videos/'.$video_data['file_name'];
		}
		
		return $return;
	}
	
	
	function edit($id = 0){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			#Validate 
			$this->form_validation->set_rules('name', $this->lang->line('name'), 'required|trim|xss_clean');
			$this->form_validation->set_rules('description', $this->lang->line('description'), 'trim|xss_clean');
			$this->form_validation->set_rules('video_url', $this->lang->line('video_url'), 'trim|xss_clean');
			if($this->form_validation->run() == TRUE){
				$user			=	$this->session->userdata('user');
				$video_name  	= 	$this->input->post('name');
				$image 			= 	$this->input->post('image');
				$image 			= 	str_replace(base_url(),"",$image);
				$video_url 		= 	$this->input->post('video_url');
				if($video_url 	== 	"Video Url"){
					$video_url	=	str_replace("Video Url", "", $video_url);
				}
				$info			=	array(
											'name'          => $video_name,
											'image_url'     => $image,
											'video_url'     => $video_url,
											'order'         => $this->input->post('order'),
											'date_create'   => date('Y-m-d'),
											'admin_create'  => $user['username'],
											'active'        => $this->input->post('status'),
											'description'	=> $this->input->post('description')
										 );
				if($this->video_model->check_exist_edit($id, $this->input->post('name'))) {
    				die('This name is exist!');
    			}elseif ($this->video_model->check_order_exist_edit($id, $this->input->post('order'))){
    				die('This order is exist !');
    			}else {
    				if($image == "") unset($info['image_url']);
    				if($_FILES['video_file']['name'] != ""){
    					#upload new video
    					$upload			=	$this->uploading();
    					$info['video']	=	$upload['video_path'];
    					
    					#remove old video
    					$old_video		=	$this->input->post('old_video');
    					if(file_exists($old_video)) {
    						unlink($old_video);
    					}
    				}else {
    					unset($info['video']);
    				}
    				$this->video_model->edit($id, $info);
    				die("yes");
    			}
				
			}
		}
		#get data info
		$info			=	$this->video_model->get_match($id);
		$data['info']	=	$info;
		$this->load->view('edit', $data);
	}
	
	
	
	function delete($id = 0){
		$info				=	$this->video_model->get_match($id);

		#unset images and thumbs
		if(isset($info->image_url) && $info->image_url != ""){
			$explosion		=	explode("/", $info->image_url);
			$name_image		=	$explosion[count($explosion)-1];
			for($i=0; $i<=3; $i++){
				$arr[]		=	$explosion[$i];
				$fo 		= 	implode("/", $arr);
			}
			
			$folder_images	=	thumbs();
			foreach ($folder_images as $k => $v){
				$file_path	=	"$fo/thumb_$v/$name_image";
				if(file_exists($file_path)){
					unlink($file_path);
				}
			}
			$main_file_path	=	"$fo/$name_image";
			if(file_exists($main_file_path)) unlink($main_file_path);
		}
		
		#unset video
		if(file_exists($info->video)) unlink($info->video);
		
		#delete in DB.
		$this->video_model->delete($id);
		 
		$delete	=	"delete video";
		$this->session->set_userdata('delete_video', $delete);
		 
		$url	=	$this->session->userdata('video_url');
		redirect($url,'refresh');
	}
	
	
	#Show form to upload thumbnail of a video
	function image(){
		$user		=	$this->session->userdata('user');
		$options    = 	$this->uri->uri_to_assoc(4);
		$upload_dir = 	'uploads/';
		$m_folder 	= 	'uploads/videos/thumbnails/';
		$root       = 	array();
		echo "option = ";
		print_r($options);
		echo "<br>";
		if(!is_dir($m_folder)) {
			create_dir($m_folder);
		}

		if(isset($options['dir'])) {
			$root = explode(':', $options['dir']);
			$upload_dir .= implode('/', $root);
		}
		if(!is_dir($upload_dir)) {
			$this->message->add('error', 'This directory is not exist !');
		}
		echo "upload_dir = ";
		echo $upload_dir;echo "<br>";
		# send data
		# directory_map('source directory') reads the directory path specified in the first parameter 
		# and builds an array representation of it and all its contained files.
		# A depth of 1 will only map the top level directory:
		$data['root']			= 	$root;
		$data['map']    		= 	directory_map($upload_dir, 1);
		$data['list_folder'] 	= 	directory_map($m_folder, 1);
		echo "data['map'] = ";
		print_r($data['map']);
		echo "<br>";//exit('no');
		echo "data['list_folder'] = ";
		print_r($data['map']);
		echo "<br>";//exit('no');
		$this->load->view('image', $data);
	}
	
	
	function thumb_upload(){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$uploadto 		=  	$this->input->post('uploadTo');
            $uploadtodir 	= 	'uploads/videos/thumbnails/'.$uploadto;
            $choosefolder 	= 	false;
        	$uri        	= 	$this->uri->uri_to_assoc(4);
			$upload_dir 	= 	'uploads/videos/thumbnails/'.date('Y_M').'/'.date('m');

			if(!empty($uploadto) && is_dir($uploadtodir)){
				$choosefolder 	= 	true;
				$upload_dir 	= 	$uploadtodir;
			}

			create_dir($upload_dir);
			
			#config for images
			$config['upload_path'] 		= $upload_dir;
			$config['allowed_types'] 	= 'gif|jpg|png';
			
			#call out image uploading library
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('art_image')) {
				$this->message->add('error', $this->upload->display_errors());
			}else {
				$img_data = $this->upload->data();		
				$new_name = $_SERVER['REQUEST_TIME'].'-'.rand(0,999999).$img_data['file_ext'];
			
				rename($img_data['full_path'], $img_data['file_path'].$new_name);
			
				# Create thumb
				$thumb_size 	= thumbs();
				$thumb_lib_dir  = thumbs_lib();

		        include_once ($thumb_lib_dir."ThumbLib.inc.php");
		        
		        $options = array(
				    'resizeUp' 		=> true,
				    'jpegQuality'	=> 88,
		        );

				foreach($thumb_size as $size){
					$thumb_dir  = $upload_dir.'/thumb_'.$size;
					create_dir($thumb_dir);
				
					$t_size = explode('_', $size);

				    $thumb 	= PhpThumbFactory::create($upload_dir."/".$new_name, $options);
				    
				    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
				    $thumb->cropFromCenter($t_size[0], $t_size[1]);
				    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
				}

                $this->message->add('success', 'The image has been uploaded successfully !');
                
                $uri['dir'] = 'videos:thumbnails:'.date('Y_M');
			}
			
			if($choosefolder==true){
				$uri['dir'] = 'videos:thumbnails:'.$uploadto;
				$url 		= admin_url("video/image/".$this->uri->assoc_to_uri($uri));
				redirect($url, 'refresh');
			}else{
				$url 		= admin_url("video/image/".$this->uri->assoc_to_uri($uri));
				redirect($url, 'refresh');
			}
			
		}
	}
	
	
	function create_directory(){
		
		$directory_name	=	$this->input->post('dir_name');
        $directory_name = ascii_link($directory_name);
        $uri      = $this->uri->uri_to_assoc(4);
        echo $directory_name;
       	
        $path     = 'uploads/videos/thumbnails/'.$directory_name;
        if(is_dir($path)) {
        	$this->message->add('error', 'This directory does exist !');
        	$uri['dir'] = 'videos:thumbnails:'.$directory_name;
        }elseif(create_dir($path)) {
            $this->message->add('success', 'Create the directory successfully !');
            $uri['dir'] = 'videos:thumbnails:'.$directory_name;
        }else {
            $this->message->add('error', 'Can not create the directory !');
            $uri['dir'] = 'videos:thumbnails';
        }
		$url	=	admin_url('video/image/'.$this->uri->assoc_to_uri($uri));
		redirect($url, 'refresh');
	}
	
	
	function selfURL(){
		if(!isset($_SERVER['REQUEST_URI'])){
			$serverrequri = $_SERVER['PHP_SELF'];
		}else{
			$serverrequri =    $_SERVER['REQUEST_URI'];
		}
		$protocol 	= strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
		$host     	= $_SERVER['HTTP_HOST'];
		$port 		= ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	
	
		$currentUrl = $protocol . '://' . $host . $port .$_SERVER['REQUEST_URI'];
	
		return $currentUrl;
	}
	
	
	function change_status(){
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$id     		= $this->input->post('id');
			$status 		= $this->input->post('status');
			 
			$info			=	array();
			$info['active']	=	$status;
			 
			$this->video_model->change_status($id, $info);
			die('yes');
		}
	}
	
	
	function load_row($id = ""){
		$data['video'] = $this->video_model->get_match($id);
		$this->load->view('row', $data);
	}
	
	
	function change_order() {
		$video_id 		= 	$this->input->post('video_id');
		$video_order 	= 	$this->input->post('video_order');
	
		$video 			= 	$this->video_model->get_match($video_id); //cate will be changed order position.
		$order		 	= 	$this->video_model->get_match_order($video_order); // Check 'order' exists or not?
	
		if (count($order) > 0) {
			$this->video_model->update_order($order['id'], array('order' => $video->order));
			$this->video_model->update_order($video_id, array('order' => $video_order));
			 
		} else {
			$this->video_model->update_order($video_id, array('order' => $video_order));
		}
	
		$url	=	$this->session->userdata('video_url');
		redirect($url, 'refresh');
	}
	
	
	function do_action(){
		if($_SERVER['REQUEST_METHOD'] == 'POST') {
			 
			$id_list = $this->input->post('id');
			$action  = $this->input->post('action');
	
			if($action == 'delete') {
				$this->video_model->delete_many($id_list);
			}
			elseif($action == 'suspend') {
				$this->video_model->update_many($id_list, array('active' => 'no'));
			}
			elseif($action == 'active') {
				$this->video_model->update_many($id_list, array('active' => 'yes'));
			}
			 
			die('yes');
		}
	}
	
} 
/*---------------------------------------------End-----------------------------------------*/